#!/usr/bin/env python

import zipfile
import tarfile

class Archiver ( object ):
	ZIP   = 1
	GZIP  = 2
	BZIP2 = 3

	UNKN  = -1

	def __init__ ( self ):
		self.file_type = 0
		self.comp = None

	def open ( self, fname, mode = 'r', force_type = -1 ):
		"""
			open ( fname, mode = 'r', force_type = -1 )

			params:
				- fname		- File name to open
				- mode		- Can be: 'r' or 'w'
				- force_type	- Force the file type, can be:
							- Archiver.ZIP
							- Archiver.BZIP2
							- Archiver.GZIP
		"""
		self.__get_file_type ( fname, force_type )

		if self.file_type == Archiver.UNKN: raise "Unknow file format for: " + fname

		if self.file_type == Archiver.ZIP:  	self.comp = zipfile.ZipFile ( fname, mode, zipfile.ZIP_DEFLATED )
		elif self.file_type == Archiver.GZIP:	self.comp = tarfile.open ( fname, mode + ':gz' )
		elif self.file_type == Archiver.BZIP2:	self.comp = tarfile.open ( fname, mode + ':bz2' )

	def close ( self ):
		self.comp.close ()

	def add ( self, fname, dest_name = 0 ):
		if not dest_name: dest_name = fname

		if self.file_type == Archiver.ZIP:
			self.comp.write ( fname, dest_name )
		else:
			tarinfo = self.comp.gettarinfo ( fname, dest_name )
    			self.comp.addfile ( tarinfo, file ( fname ) )



	def __get_file_type ( self, fname, force_type = -1 ):
		if fname.endswith ( ".zip" ): self.file_type = Archiver.ZIP
		elif fname.endswith ( ".gz" ): self.file_type = Archiver.GZIP
		elif fname.endswith ( ".tgz" ): self.file_type = Archiver.GZIP
		elif fname.endswith ( ".bz2" ): self.file_type = Archiver.BZIP2
		elif fname.endswith ( ".tbz2" ): self.file_type = Archiver.BZIP2
		else: self.file_type = force_type
		

if __name__ == '__main__':
	a = Archiver ()
	a.open ( 'pizza.tar.zip', 'w' )
	for f in ( 'archiver.py', 'thread_control.py', 'zip_handler.py' ):
		a.add ( f, 'fake_dir/' + f )

	a.close ()
	

	
		
